package cn.wolfcode.exception;

import cn.wolfcode.qo.JSONResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * 利用AOP 对控制器增强
 * 处理控制器出现的异常
 */
@ControllerAdvice
public class HandlerControllerException {

    /**
     * @ExceptionHandler代表当前的方法是处理异常,处理什么异常
     * 处理运行时异常
     *
     */
    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(RuntimeException ex, HttpServletResponse response, HandlerMethod method){

        ex.printStackTrace(); //方便开发找bug

        //判断有没有贴@ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)){

            String errorMsg = "操作失败";
            if (ex instanceof LogicException){ //判断是否逻辑异常,如果是,直接用异常自己的错误信息

                errorMsg = ex.getMessage();
            }
            JSONResult json = new JSONResult(false, errorMsg);
            response.setContentType("application/jsonResult;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }else {

            return "common/error";
        }


    }


    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerUnauthorized(RuntimeException e, HttpServletResponse response, HandlerMethod method) throws IOException {

        e.printStackTrace(); //方便开发找bug

        //判断有没有贴@ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)){


            JSONResult json = new JSONResult(false, "你没有权限操作");
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));

            } catch(Exception e1) {
                e1.printStackTrace();
            }
            return null;
        }else {

            return "common/nopermission";
        }


    }

}
